Page({
    data: {
        productsWithComments: [], // 存储有评价的产品
        cmtVisible:false,
        cmtText:'',
        cmtPid:null
    },

    onLoad(){
        // 从缓存读取最新数据
        const products = wx.getStorageSync('products') || []
        // 筛选出有评价的产品
        const productsWithComments = products.filter(p => p.comment)
        this.setData({ productsWithComments })
        // 设置导航栏标题
        wx.setNavigationBarTitle({title: '我的评价'})
      },

    onShow(){
        // 从缓存读取最新数据
        const products = wx.getStorageSync('products') || []
        // 筛选出有评价的产品
        const productsWithComments = products.filter(p => p.comment)
        this.setData({ productsWithComments })
      },
      initProducts(){
        const list = [
            {id:1,title:'鲜肉月饼',price:7999,thumb:'https://ts1.tc.mm.bing.net/th/id/OIP-C.Fe3G12jGnzA5-E9ozhJ5HAHaLH?rs=1&pid=ImgDetMain&o=7&rm=3=鲜肉月饼'},
            {id:2,title:'',price:1899,thumb:'https://img.shetu66.com/2023/11/24/1700771295543366.png=大麦茶'}
        ]
        wx.setStorageSync('products',list)
        return list
      },
    /* 点赞 */
    like(e){
        const id = e.currentTarget.dataset.id
        const products = wx.getStorageSync('products')
        const p = products.find(v=>v.id===id)
        if(!p.comment.liked){
          p.comment.likes = (p.comment.likes||0)+1
          p.comment.liked = true
        }else{
          p.comment.likes -= 1
          p.comment.liked = false
        }
        wx.setStorageSync('products',products)
        // 更新productsWithComments数组而不是products
        const productsWithComments = products.filter(p => p.comment)
        this.setData({ productsWithComments })
      },
    
      /* 评论相关 */
      showCmtInput(e){
        this.setData({cmtVisible:true,cmtPid:e.currentTarget.dataset.id,cmtText:''})
      },
      onCmtInput(e){this.setData({cmtText:e.detail.value})},
      sendCmt(){
        if(!this.data.cmtText.trim()) return
        const products = wx.getStorageSync('products')
        const p = products.find(v=>v.id===this.data.cmtPid)
        if(!p.comment.replies) p.comment.replies=[]
        // 添加评论时间
        p.comment.replies.push({
          nick:'微信用户',
          text:this.data.cmtText,
          time: this.formatTime(new Date())
        })
        wx.setStorageSync('products',products)
        // 更新productsWithComments数组而不是products
        const productsWithComments = products.filter(p => p.comment)
        this.setData({ productsWithComments, cmtVisible:false })
      },

    // 关闭评论弹窗
    closeCmt(){
        this.setData({cmtVisible:false})
      },

    // 阻止事件冒泡
    stopPropagation(){
        // 空函数，仅用于阻止事件冒泡
      },

    // 跳转到评论页面
    goToComment(){
        if(this.data.currentProduct){
          wx.navigateTo({
            url: `/pages/comment/comment?id=${this.data.currentProduct.id}`
          })
        }
      },
    
      /* 预览图片 */
      preview(e){
        wx.previewImage({urls:[e.currentTarget.dataset.src]})
      },
  
    // 加载朋友圈数据
    loadMomentData(index) {
      const storedMoments = wx.getStorageSync('momentsData') || [];
      this.setData({
        moment: storedMoments[index]
      });
    },
  
    // 点赞功能
    toggleLike() {
      const storedMoments = wx.getStorageSync('momentsData') || [];
      const currentMoment = storedMoments[this.data.index];
      
      if (currentMoment.isLiked) {
        // 取消点赞
        currentMoment.isLiked = false;
        currentMoment.likeCount--;
      } else {
        // 点赞
        currentMoment.isLiked = true;
        currentMoment.likeCount++;
      }
      
      storedMoments[this.data.index] = currentMoment;
      wx.setStorageSync('momentsData', storedMoments);
      
      this.setData({
        moment: currentMoment
      });
      
      wx.showToast({
        title: currentMoment.isLiked ? '点赞成功' : '取消点赞',
        icon: 'none'
      });
    },
  
    // 显示评论输入框
    showCommentInput() {
      this.setData({
        showCommentInput: true,
        commentContent: ''
      });
      
      // 自动聚焦，弹出键盘
      setTimeout(() => {
        const query = wx.createSelectorQuery();
        query.select('#commentInput').focus();
        query.exec();
      }, 100);
    },
  
    // 评论内容变化
    onCommentChange(e) {
      this.setData({
        commentContent: e.detail.value
      });
    },
  
    // 发送评论
    sendComment() {
      const content = this.data.commentContent.trim();
      if (!content) {
        wx.showToast({
          title: '评论不能为空',
          icon: 'none'
        });
        return;
      }
  
      const storedMoments = wx.getStorageSync('momentsData') || [];
      const currentMoment = storedMoments[this.data.index];
      
      // 初始化评论数组
      if (!currentMoment.comments) {
        currentMoment.comments = [];
      }
      
      // 添加新评论
      currentMoment.comments.push({
        user: '我',
        content: content,
        time: this.formatTime(new Date())
      });
      
      // 更新评论数量
      currentMoment.commentCount = currentMoment.comments.length;
      
      // 保存数据
      storedMoments[this.data.index] = currentMoment;
      wx.setStorageSync('momentsData', storedMoments);
      
      // 更新页面
      this.setData({
        moment: currentMoment,
        commentContent: '',
        showCommentInput: false
      });
      
      wx.showToast({
        title: '评论成功',
        icon: 'none'
      });
    },
  
    // 分享功能
    onShareAppMessage() {
      const moment = this.data.moment;
      return {
        title: '朋友圈分享',
        path: '/pages/detail/detail?index=' + this.data.index,
        imageUrl: moment.images.length > 0 ? moment.images[0] : ''
      };
    },
  
    // 格式化时间
    formatTime(date) {
      const year = date.getFullYear()
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hour = date.getHours()
      const minute = date.getMinutes()

      return `${year}-${this.padZero(month)}-${this.padZero(day)} ${this.padZero(hour)}:${this.padZero(minute)}`
    },

    // 补零函数
    padZero(n) {
      return n < 10 ? '0' + n : n
    },
  });
      